<?php
class HtmlToTextHelper extends AppHelper {
	
	/**
	 * Izchistva podadeniqt html text, kato premahva vsichki html tagove i vryshta chist text.
	 * Prametri:
	 * 	
	 * 	$html - html texta za izchistvane
	 * 	
	 * 	$maxSymbols - maximum simvoli, koito trqbva da se varnat v chist text
	 * 	
	 * 	$cutByWord - ako e true, togava nqma da reji chistiq text simvol po simvol,
	 *  ami shte se razdeli po celi dumi.
	 *  Taka ako dadenata duma nadhvyrlq limita $maxSymbols togava se vryshta na predishnata duma.
	 * 
	 * @param String $html
	 * @param Integer $maxSymbols
	 * @param Boolean $cutByWord
	 * @return String
	 */
	function html2text($html = null, $maxSymbols = 0, $cutByWord = false, $encoding = 'UTF-8') {
	//=====================================================================================
		$theHTML = $html;
		$theTEXT = '';
		
		//------- premahvame html tagovete
		$ltIndex = mb_strpos($theHTML, '<', 0, $encoding);
		$gtIndex = mb_strpos($theHTML, '>', 0, $encoding);
		
		while((!($ltIndex===FALSE)) && (!($gtIndex===FALSE))) {
			$theHTML = mb_substr($theHTML, 0, $ltIndex, $encoding).mb_substr($theHTML, ($gtIndex+1), mb_strlen($theHTML, $encoding), $encoding);
			
			$ltIndex = mb_strpos($theHTML, '<', 0, $encoding);
			$gtIndex = mb_strpos($theHTML, '>', 0, $encoding);
		}
		//------/ premahvame html tagovete
		
		$theTEXT = $theHTML; // inicializirame veche s preraboten "chist" html
		
		if($maxSymbols==0) {
			return $this->output($theTEXT);
		}
		
		if((!$cutByWord) || ($maxSymbols >= mb_strlen($theTEXT, $encoding))) {
			$theTEXT = mb_substr($theTEXT, 0, $maxSymbols, $encoding);
		} else {
			// ako sme prekusnali duma, kato q izrqzvame .. togava se vryshtame do sreshtaneto na prazen interval. ELSE si izrqzvame normalno
			if(strcmp(mb_substr($theTEXT, ($maxSymbols-1), 1, $encoding), ' ') != 0) {				
				$theTEXT = mb_substr($theTEXT, 0, $maxSymbols, $encoding);
				
				$previousWordIndex = mb_strrpos($theTEXT, ' ', -1, $encoding);
				
				if($previousWordIndex===FALSE) {
					$theTEXT = mb_substr($theTEXT, 0, $maxSymbols, $encoding);
				} else {
					$theTEXT = mb_substr($theTEXT, 0, $previousWordIndex, $encoding);
				}
			} else {
				$theTEXT = mb_substr($theTEXT, 0, $maxSymbols, $encoding);
			}
		}
		
		return $this->output($theTEXT);
	}
	
}
?>
